<?php
declare (strict_types = 1);

namespace app\product\controller;

use app\product\BaseController;
use app\auth\common\util\ApiUtil;
use app\product\service\CategoryService;

class CategoryController extends BaseController
{
    public function __construct(CategoryService $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    public function list(){
        $params = request()->param();
        $where = $limit = array();
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $pid = intval($params['pid'])??0;
        $where[] = ['pid','=',$pid];
        $list = $this->categoryService->list($where , $limit);
        return ApiUtil::normal($list);
    }

    public function tree(){
        $list = $this->categoryService->select();
        if(empty($list)) return ApiUtil::normal('', '暂无分类',ApiUtil::CODE_FAIL);
        $forums = $this->categoryService->tree($list->toArray());
        return ApiUtil::normal($forums);
    }

    public function add(){
        $pid = input('pid',0);
        $name = input('name','');
        if(empty($name)) return ApiUtil::normal('', '分类名称不能为空',ApiUtil::CODE_FAIL);
        $data = array();
        $data['pid'] = $pid;
        $data['name'] = $name;
        $data['create_uid'] = request()->admin_id;
        $data['create_time'] = time();
        $lastId = $this->categoryService->insertGetId($data);
        if(!$lastId) return ApiUtil::normal('', '添加失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal( ['id'=>$lastId]);
    }

    public function edit(){
        $id = input('id',0);
        if(empty($id)) return ApiUtil::normal('', '分类ID不能为空',ApiUtil::CODE_FAIL);
        $pid = input('pid',0);
        $name = input('name','');
        if(empty($name)) return ApiUtil::normal('', '分类名称不能为空',ApiUtil::CODE_FAIL);
        $data = array();
        $data['pid'] = $pid;
        $data['name'] = $name;
        $data['create_uid'] = request()->admin_id;
        $update = $this->categoryService->update(['id'=>$id],$data);
        if(!$update) return ApiUtil::normal('', '编辑失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal(['id'=>$id]);
    }

    public function delete(){
        $id = (string)input('id','');
        if(empty($id)) return ApiUtil::normal(null, 'ID不能为空', ApiUtil::CODE_FAIL);
        $ids = explode(',', $id);
        // 查看该分类是否存在子分类，存在则不允许删除
        $subcate = $this->categoryService->count([],['pid',$ids]);
        if($subcate) return ApiUtil::normal(null,'', '删除的分类下还存在子分类！', ApiUtil::CODE_FAIL);
        $del = $this->categoryService->delete(['id',$ids]);
        if(!$del) return ApiUtil::normal('', '删除失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal(['id'=>$ids]);
    }
}
